package com.kangye.learnteacher.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kangye.learnteacher.entity.*;
import com.kangye.learnteacher.mapper.QuestionBankMapper;
import com.kangye.learnteacher.mapper.StageMapper;
import com.kangye.learnteacher.service.QuestionBankService;
import com.kangye.learnteacher.util.DownloadFileUtil;
import com.kangye.learnteacher.util.ExcelImportUtils;
import com.kangye.learnteacher.util.RedisStorageUtil;
import com.kangye.learnteacher.util.ViewJsonObject;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @program: learndeduo
 * @description: 题库逻辑接口实现类
 * @author: 苗伟晨
 * @create: 2021-05-17 17:47
 **/
@Service
public class QuestionBankServiceImpl implements QuestionBankService {
    @Autowired
    private QuestionBankMapper questionBankMapper;
    @Autowired
    private ViewJsonObject<QuestionBank> viewJsonObject;

    @Autowired
    private RedisStorageUtil redisStorageUtil;
    @Autowired
    private ExcelImportUtils excelImportUtils;
    @Autowired
    DownloadFileUtil downloadFileUtil;

    @Autowired
    private StageMapper stageMapper;
    @Override
    public ViewJsonObject<Map<String, Object>> queryAllQuestionBank(Integer page, Integer limit, Integer qb_id, String subject_name, Integer gradeId, String type_name) {
        ViewJsonObject<Map<String,Object>> viewJsonObject = new ViewJsonObject<>();
        PageHelper.startPage(page,limit);
        List<Map<String, Object>> mapList = questionBankMapper.queryAllQuestionBank(qb_id, subject_name, gradeId, type_name);
        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>(mapList);
        viewJsonObject.setData(pageInfo.getList());
        viewJsonObject.setCount(pageInfo.getTotal());
        viewJsonObject.setCode(0);
        viewJsonObject.setMsg("");
        return viewJsonObject;
    }

    @Override
    public Map deleteById(Integer qb_id) {
        Map<String,Object> map = new HashMap<>();
        boolean i =this.questionBankMapper.deleteById(qb_id) > 0;
        if (i = true){
            map.put("code",0);
        }else {
            map.put("code",-1);
        }
        return map;
    }
    /**
     * 查询题型
     * */
    @Override
    public ViewJsonObject<QuestionBank> querySubject(QuestionBank questionBank) {
        List<QuestionBank> querySubject = questionBankMapper.querySubject(questionBank);
        if (querySubject.size() > 0){
            viewJsonObject.setCode(0);
            viewJsonObject.setCount(3L);
            viewJsonObject.setData(querySubject);
            viewJsonObject.setMsg("");
        }
        return viewJsonObject;
    }

    @Override
    public List<Map<String, Object>> queryById(Integer qb_id) {
        List<Map<String, Object>> maps = questionBankMapper.queryById(qb_id);
        System.out.println(maps);
        //存放到redis中
        redisStorageUtil.addObjOne("queryById",maps,5,TimeUnit.MINUTES);
        Object queryByIds = redisStorageUtil.getKeyOne("queryById");
        System.out.println("redis"+queryByIds);
        return maps;
    }
    /**
     * 添加单行
     * */
    public Integer insert(QuestionBank questionBank){
        return questionBankMapper.insert(questionBank);
    }

    /**
     * 创建文件
     * @param fileName 文件名
     * @param file 文件流
     */
    @Override
    public String batchImport(String fileName, MultipartFile file) {
        File uploadDir = null;
        try {
            uploadDir = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //创建一个目录 （它的路径名由当前 File 对象指定，包括任一必须的父路径。）
        if (!uploadDir.exists()) uploadDir.mkdirs();
        //新建一个临时文件
        File tempFile = new File("E:\\" + UUID.randomUUID() + ".xlsx");
        //初始化输入流
        InputStream is = null;
        try {
            //将上传的文件写入新建的文件中
            file.transferTo(tempFile);

            //根据新建的文件实例化输入流
            is = new FileInputStream(tempFile);

            //根据版本选择创建Workbook的方式
            Workbook wb = null;
            //根据文件名判断文件是2003版本还是2007版本
            if (excelImportUtils.isExcel2007(fileName)) {
                wb = new XSSFWorkbook(is);
            } else {
                wb = new HSSFWorkbook(is);
            }
            //根据excel里面的内容读取知识库信息
            return readExcelValue(wb, tempFile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    is = null;
                    e.printStackTrace();
                }
            }
        }
        return "文件类型错误!请重新下载模板";
    }

    /**
     * 解析Excel里面的数据
     *
     * @param wb
     * @param tempFile
     * @return  提示信息
     */
    private String readExcelValue(Workbook wb, File tempFile) {
        List<QuestionBank> qbList = new ArrayList<>();
        //错误信息接收器
        String errorMsg = "";
        //得到第一个shell
        Sheet sheet = wb.getSheetAt(0);
        //得到Excel的行数
        int totalRows = sheet.getPhysicalNumberOfRows();
        //循环Excel行数,从第二行开始。标题不入库
        for (int r = 1; r < totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                //跳过空行
                continue;
            }
            //创建questionBank对象
            //循环Excel的列
            QuestionBank qB = new QuestionBank();

            try {
                //年级判空
                if (row.getCell(6).toString()==null || row.getCell(6).toString() ==""){
                    errorMsg = "第" + (r + 1) + "年级不能为空!请修改后在上传";
                    tempFile.delete();
                    return errorMsg;
                }
                Grade grade = stageMapper.selectByName(row.getCell(6).toString());
                row.getCell(6).setCellType(CellType.STRING);
                qB.setQbGradeId(grade.getGradeId());

                //题型判空
                if (row.getCell(7).toString()==null || row.getCell(7).toString() ==""){
                    errorMsg = "第" + (r + 1) + "班级不能为空!请修改后在上传";
                    tempFile.delete();
                    return errorMsg;
                }
                TypeQuestion typeQuestion = stageMapper.selectTqName(row.getCell(7).toString());
                row.getCell(7).setCellType(CellType.STRING);
                qB.setQbQuestionId(typeQuestion.getTypeId());
                //判断题干
                row.getCell(0).setCellType(CellType.STRING);
                qB.setQbName(row.getCell(0).toString());
                //判断选项
                row.getCell(1).setCellType(CellType.STRING);
                qB.setQbOptions(row.getCell(1).toString());
                //标答
                row.getCell(2).setCellType(CellType.STRING);
                qB.setQbAnswer(row.getCell(2).toString());
                //分数
                row.getCell(3).setCellType(CellType.STRING);
                qB.setQbScore(BigDecimal.valueOf(Double.valueOf(row.getCell(3).toString())));

                //难度
                row.getCell(4).setCellType(CellType.STRING);
                qB.setQbDifficulty(Integer.parseInt(row.getCell(4).toString()));
                //学科判空
                if (row.getCell(5).toString()==null || row.getCell(5).toString() ==""){
                    errorMsg = "第" + (r + 1) + "学科不能为空!请修改后在上传";
                    tempFile.delete();
                    return errorMsg;
                }
                Subject subject = stageMapper.selectSubName(row.getCell(5).toString(),grade.getGradeId());
                row.getCell(5).setCellType(CellType.STRING);
                qB.setQbSubjectId(subject.getSubjectId());
            } catch (NullPointerException e) {
                errorMsg = "第" + (r + 1) + "行数据出错!请修改后在上传";
                tempFile.delete();
                return errorMsg;
            }
            qbList.add(qB);
        }
        //删除上传的临时文件
        if (tempFile.exists()) {
            tempFile.delete();
        }
        //遍历添加数据
        for (QuestionBank i : qbList) {
            insert(i);
        }
        errorMsg = "上传完成";
        return errorMsg;
    }


}

